var cf = require('../lib/config.js');

function ajax(url, data, s, f) {
  wx.request({
    url: url,
    data: data,
    method: "post",
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {

      s && s(res);
    },
    fail: function(res) {
      f && f(res)
    }
  })
}

function verlogin(that) {
  var uinfo = wx.getStorageSync('userinfo');
  if (!uinfo) {
    that.setData({
      showlogin: 1
    });
  }
}

function phoneVer(phone) {
  var phoneReg = /(^1[3|4|5|7|8]\d{9}$)|(^09\d{8}$)/;
  if (!phoneReg.test(phone)) {
    wx.showToast({
      title: '手机号码有误',
      image: '/images/closered.png',
    })
    wx.hideLoading()
    return;
  }
  return;
}

//距离计算价钱
function getAmountInfo(distance, weight, that, money) {
  console.log('distance--' + distance);
  console.log('weight--' + weight);
  console.log('money--' + money);
  ajax(
    cf.hostapi + 'getAmountInfo', {
      distance: distance,
      weight: 0,
      add_money: 0
    },
    res => {
      that.setData({
        price: res.data.data.price
      })
    }
  )
  ajax(
    cf.hostapi + 'getAmountInfo', {
      distance: distance,
      weight: weight,
      add_money: money
    },
    res => {
      console.log(res);
      that.setData({
        total_price: res.data.data.price,
        integral: res.data.data.integral,
      })
    }
  )
}

function tuup(that, imgurl, status, orderid, list, index) {

  wx.chooseImage({
    count: 1, // 默认9
    success: (res) => {
      var i = 0; //第几个
      var img_num = res.tempFiles.length;
      wx.uploadFile({
        url: cf.hostapi + 'Uploads',
        filePath: res.tempFilePaths[i],
        name: 'image',
        pathname: 'sendpet',
        success: (res) => {
          console.log(res.data);
          var data = JSON.parse(res.data.replace(/^\s+|\s+$/g, ""));
          var imgid = data.data;
          that.setData({
            imgid: imgid
          });
          ajax(
            cf.hostapi + 'toIdGetUrlInfo', {
              id: imgid
            },
            res => {
              if (res.data) {
                console.log(list);
                var hosturl = cf.hosturl;
                // that.setData({
                //   [imgurl]: hosturl + res.data,
                // })
                console.log(status);
                console.log(hosturl + res.data);
                if (status =='tack_pic'){
                  that.setData({ [`list[${index}].tack_pic`]: hosturl + res.data });
                }else{
                  that.setData({ [`list[${index}].give_pic`]: hosturl + res.data });
                }
                // console.log('hosturl'+hosturl + res.data);
                  ajax(
                    cf.hostapi + 'edittackgivePic', { order_id: orderid, [status]: imgid},
                    res => {
                      var listn = list[index];

                      console.log(that.data.list);
                    }
                  )
              };

            }
          )
        }
      });
    },
  });
}

//计算距离并且 计算出价钱
function distance(la1, lo1, la2, lo2, that) {
  var weight = that.data.weight;
  var La1 = la1 * Math.PI / 180.0;
  var La2 = la2 * Math.PI / 180.0;
  var La3 = La1 - La2;
  var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
  s = s * 6378.137; //地球半径
  s = Math.round(s * 10000) / 10000;
  if (s < 1) {
    var m = Math.round(s * 1000) + 'm';
    that.setData({
      awary: m,
      s: s
    });
  } else {
    var m = Math.round(s) + 'km';
    that.setData({
      awary: m,
      s: s
    });
  }
  that.setData({
    s: s
  })
}
//通过地址id 获取地址信息  并且 不需要有money和重量字段才计算记录和价钱
function toTwoAddressIdGetInfo(id, that, status, type) {
  console.log('status--' + status);

  ajax(
    cf.hostapi + 'toIdGetAddressInfo', {
      id: id
    },
    res => {
      if (status == 'qu') {
        that.setData({
          quaddress: res.data.data.details, //用于给前端显示地址
          quaddressinfo: res.data.data,
        })
        if (typeof(that.data.huoddressinfo) != 'undefined') {
          var huoddressinfo = that.data.huoddressinfo;
          var quaddressinfo = that.data.quaddressinfo;
          console.log(quaddressinfo);
          var lat1 = huoddressinfo.lat;
          var lng1 = huoddressinfo.lng;
          var lat2 = quaddressinfo.lat;
          var lng2 = quaddressinfo.lng;
          distance(lat1, lng1, lat2, lng2, that); //获取两点距离
          getAmountInfo(that.data.s, 0, that, 0)
        }
      } else {
        var huoddressinfo = res.data.data;
        that.setData({
          huoddress: res.data.data.details,
          huoddressinfo: res.data.data
        });
        if (typeof(that.data.quaddressinfo) != 'undefined') {
          var quaddressinfo = that.data.quaddressinfo;
          var lat1 = huoddressinfo.lat;
          var lng1 = huoddressinfo.lng;
          var lat2 = quaddressinfo.lat;
          var lng2 = quaddressinfo.lng;
          distance(lat1, lng1, lat2, lng2, that); //获取两点距离
          getAmountInfo(that.data.s, 0, that, 0)
        }
      }




    }
  )
}
//通过地址id 获取地址信息  不需要计算出距离
function toAddressIdGetInfono(id, that) {
  ajax(
    cf.hostapi + 'toIdGetAddressInfo', {
      id: id
    },
    res => {
      console.log(res.data.data);
      that.setData({
        quaddress: res.data.data.details, //用于给前端显示地址
        quaddressinfo: res.data.data,
      })
      getAmountInfo(0, 0, that, 0);
    }
  )
}
//通过地址id 获取地址信息  并且 必须有money和重量字段才计算记录和价钱
function toAddressIdGetInfo(id, that, status, type) {
  console.log('status--' + status);
  if (type = 'money') {
    var typeinfo = that.data.money;
  } else {
    var typeinfo = that.data.weight;
  }
  ajax(
    cf.hostapi + 'toIdGetAddressInfo', {
      id: id
    },
    res => {
      if (status == 'qu') {
        that.setData({
          quaddress: res.data.data.details, //用于给前端显示地址
          quaddressinfo: res.data.data,
        })
        if (typeof(that.data.huoddressinfo) != 'undefined' && typeof(typeinfo) != 'undefined') {
          var huoddressinfo = that.data.huoddressinfo;
          var quaddressinfo = that.data.quaddressinfo;
          console.log(quaddressinfo);
          var lat1 = huoddressinfo.lat;
          var lng1 = huoddressinfo.lng;
          var lat2 = quaddressinfo.lat;
          var lng2 = quaddressinfo.lng;
          distance(lat1, lng1, lat2, lng2, that);
          getAmountInfo(that.data.s, that.data.weight, that, that.data.money)
        }
      } else {
        var huoddressinfo = res.data.data;
        that.setData({
          huoddress: res.data.data.details,
          huoddressinfo: res.data.data
        });
        if (typeof(that.data.quaddressinfo) != 'undefined' && typeof(typeinfo) != 'undefined') {
          var quaddressinfo = that.data.quaddressinfo;
          var lat1 = huoddressinfo.lat;
          var lng1 = huoddressinfo.lng;
          var lat2 = quaddressinfo.lat;
          var lng2 = quaddressinfo.lng;
          distance(lat1, lng1, lat2, lng2, that);
          getAmountInfo(that.data.s, that.data.weight, that, that.data.money)
        }
      }




    }
  )
}
//点击授权按钮
function clicklogin(e, that) {
  //点击授权获取用户基本信息
  var userinfo = JSON.parse(e.detail.rawData);
  var avaurl = userinfo.avatarUrl;
  var nick = userinfo.nickName;
  var sex = userinfo.gender;
  var type = 2;
  //登录获取用户code
  wx.showLoading({
    title: '登录中！',
    mask: true,
    success: function(res) {},
    fail: function(res) {},
    complete: function(res) {},
  })
  wx.login({

    success: function(res) {
      var code = res.code;
      ajax(
        cf.hostapi + 'wechatLogin', {
          code: code,
          avaurl: avaurl,
          nick: nick,
          sex: sex,
          type: type
        },
        res => {
          console.log(res);
          var uid = res.data.data.uid;
          ajax(
            cf.hostapi + 'getriderinfotiid', {
              id: uid
            },
            res => {
              if (res.data.retcode == 200) {
                wx.showToast({
                  title: '登录成功！',
                  image: '/images/dui.png'
                })
                wx.hideLoading();
                wx.setStorageSync('userinfo', res.data.data);
                that.setData({
                  showlogin: 0
                })
                that.onLoad();
              };
            }
          )
        }
      )
    },
    fail: function(res) {},
    complete: function(res) {},
  })
}

function getLngLatInfo() {
  console.log('getLngLatInfo');
  wx.getLocation({
    type: 'wgs84',
    success(res) {
      console.log(res);
      var latitude = res.latitude
      var longitude = res.longitude
      var speed = res.speed
      var accuracy = res.accuracy
      var rid = wx.getStorageSync('userinfo').id;
      ajax(
        cf.hostapi + 'getLngLatInfo', {
          riderid: rid,
          lat: latitude,
          lng: longitude
        },
        res => {
          console.log(res);
        }
      )
    }
  })
}

module.exports = {
  ajax: ajax,
  phoneVer: phoneVer,
  getAmountInfo: getAmountInfo,
  tuup: tuup,
  distance: distance,
  toAddressIdGetInfo: toAddressIdGetInfo,
  toAddressIdGetInfono: toAddressIdGetInfono,
  toTwoAddressIdGetInfo: toTwoAddressIdGetInfo,
  verlogin: verlogin,
  clicklogin: clicklogin,
  getLngLatInfo: getLngLatInfo
}